package tk.winshu.shortestpath.util;

import java.awt.geom.Point2D;

/**
 * 移动工具类
 *
 * @author Jason Krebs
 * @date 2015年2月6日
 */
public class MoveUtil {

    private static final int STEP = 8;

    /**
     * 计算下一位置
     *
     * @param current 当前位置
     * @param source  起始位置
     * @param target  终点位置
     * @return 下一位置
     */
    public static Point2D nextLocation(Point2D current, Point2D source, Point2D target) {
        if (current.equals(target)) {
            return source;
        }

        if (Math.abs(current.getX() - target.getX()) <= STEP && Math.abs(current.getY() - target.getY()) <= STEP) {
            return target;
        }

        double x1 = source.getX();
        double y1 = source.getY();
        double x2 = target.getX();
        double y2 = target.getY();

        int directionX = x1 < x2 ? 1 : -1;
        int directionY = y1 < y2 ? 1 : -1;

        // 垂直线,k=∞
        if (x1 == x2) {
            return new Point2D.Double(target.getX(), current.getY() + STEP * directionY);
        }

        double k = (y2 - y1) / (x2 - x1);
        double stepX = STEP / (Math.sqrt(k * k + 1));
        double stepY = Math.abs(k) * stepX;

        return new Point2D.Double(current.getX() + stepX * directionX, current.getY() + stepY * directionY);
    }
}
